const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');
const crypto = require('crypto');

// 密码加密
function encryptPassword(password) {
  return crypto.createHash('md5').update(password).digest('hex');
}

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, password, name, phone } = req.body;
    
    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM sys_user WHERE username = ? AND is_deleted = 0',
      [username]
    );

    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 检查手机号是否已存在
    if (phone) {
      const [existingPhones] = await pool.execute(
        'SELECT id FROM sys_user WHERE phone = ? AND is_deleted = 0',
        [phone]
      );

      if (existingPhones.length > 0) {
        return res.status(400).json({
          success: false,
          message: '手机号已被注册'
        });
      }
    }

    // 加密密码
    const encryptedPassword = encryptPassword(password);

    // 创建用户
    const [result] = await pool.execute(
      'INSERT INTO sys_user (username, password, name, phone, status) VALUES (?, ?, ?, ?, 1)',
      [username, encryptedPassword, name || '', phone || '']
    );

    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        id: result.insertId,
        username,
        name: name || '',
        phone: phone || ''
      }
    });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败',
      error: error.message
    });
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    const encryptedPassword = encryptPassword(password);

    // 查询用户
    const [users] = await pool.execute(
      'SELECT id, username, name, phone, avatar, description, status FROM sys_user WHERE username = ? AND password = ? AND is_deleted = 0',
      [username, encryptedPassword]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const user = users[0];

    if (user.status === 0) {
      return res.status(401).json({
        success: false,
        message: '账户已被禁用'
      });
    }

    // 更新最后登录时间（在user_info表中）
    await pool.execute(
      'UPDATE user_info SET last_login_time = NOW(), last_login_ip = ? WHERE username = ?',
      [req.ip || '127.0.0.1', username]
    );

    // 生成token（简单实现，实际项目应使用JWT）
    const token = `Admin Token_${user.id}_${Date.now()}`;

    res.json({
      code: 200,
      data: {
        token: token
      }
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败',
      error: error.message
    });
  }
});

// 根据token获取用户信息
router.get('/info', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供token'
      });
    }

    // 从token中解析用户ID（简单实现，实际项目应使用JWT）
    let userId;
    if (token.includes('Admin Token_')) {
      userId = parseInt(token.split('_')[1]);
    } else {
      return res.status(401).json({
        code: 401,
        message: '无效的token'
      });
    }

    const [users] = await pool.execute(
      'SELECT id, username, name, phone, avatar, description, status, create_time FROM sys_user WHERE id = ? AND is_deleted = 0',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }

    const user = users[0];
    
    // 获取用户角色信息
    const [roles] = await pool.execute(
      'SELECT r.role_name FROM sys_user_role ur JOIN sys_role r ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.is_deleted = 0',
      [userId]
    );
    
    const roleNames = roles.map(r => r.role_name);

    res.json({
      code: 200,
      data: {
        checkUser: {
          userId: user.id,
          avatar: user.avatar || "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
          username: user.username,
          password: "******", // 不返回真实密码
          desc: user.description || "平台管理员",
          roles: roleNames.length > 0 ? roleNames : ["平台管理员"],
          buttons: ["cuser.detail"], // 默认按钮权限
          routes: ["home"], // 默认路由权限
          token: token
        }
      }
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取用户信息失败',
      error: error.message
    });
  }
});

// 获取用户信息
router.get('/profile/:id', async (req, res) => {
  try {
    const userId = req.params.id;
    
    const [users] = await pool.execute(
      'SELECT id, username, name, phone, avatar, description, status, create_time FROM sys_user WHERE id = ? AND is_deleted = 0',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }

    const user = users[0];
    
    // 获取用户角色信息
    const [roles] = await pool.execute(
      'SELECT r.role_name FROM sys_user_role ur JOIN sys_role r ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.is_deleted = 0',
      [userId]
    );
    
    const roleNames = roles.map(r => r.role_name);

    res.json({
      code: 200,
      data: {
        checkUser: {
          userId: user.id,
          avatar: user.avatar || "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
          username: user.username,
          password: "******", // 不返回真实密码
          desc: user.description || "平台管理员",
          roles: roleNames.length > 0 ? roleNames : ["平台管理员"],
          buttons: ["cuser.detail"], // 默认按钮权限
          routes: ["home"], // 默认路由权限
          token: "Admin Token" // 这里应该从token中解析或重新生成
        }
      }
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取用户信息失败',
      error: error.message
    });
  }
});

// 更新用户信息
router.put('/profile/:id', async (req, res) => {
  try {
    const userId = req.params.id;
    const { name, phone, avatar, description } = req.body;

    // 检查用户是否存在
    const [users] = await pool.execute(
      'SELECT id FROM sys_user WHERE id = ? AND is_deleted = 0',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 检查手机号是否被其他用户使用
    if (phone) {
      const [existingPhones] = await pool.execute(
        'SELECT id FROM sys_user WHERE phone = ? AND id != ? AND is_deleted = 0',
        [phone, userId]
      );

      if (existingPhones.length > 0) {
        return res.status(400).json({
          success: false,
          message: '手机号已被其他用户使用'
        });
      }
    }

    // 更新用户信息
    await pool.execute(
      'UPDATE sys_user SET name = ?, phone = ?, avatar = ?, description = ? WHERE id = ?',
      [name || '', phone || '', avatar || '', description || '', userId]
    );

    res.json({
      success: true,
      message: '更新用户信息成功'
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败',
      error: error.message
    });
  }
});

// 修改密码
router.put('/password/:id', async (req, res) => {
  try {
    const userId = req.params.id;
    const { oldPassword, newPassword } = req.body;

    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '旧密码和新密码不能为空'
      });
    }

    // 验证旧密码
    const encryptedOldPassword = encryptPassword(oldPassword);
    const [users] = await pool.execute(
      'SELECT id FROM sys_user WHERE id = ? AND password = ? AND is_deleted = 0',
      [userId, encryptedOldPassword]
    );

    if (users.length === 0) {
      return res.status(400).json({
        success: false,
        message: '旧密码错误'
      });
    }

    // 更新密码
    const encryptedNewPassword = encryptPassword(newPassword);
    await pool.execute(
      'UPDATE sys_user SET password = ? WHERE id = ?',
      [encryptedNewPassword, userId]
    );

    res.json({
      success: true,
      message: '修改密码成功'
    });
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({
      success: false,
      message: '修改密码失败',
      error: error.message
    });
  }
});

// 获取用户列表（管理员功能）
router.get('/', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    const search = req.query.search || '';

    let whereClause = 'WHERE is_deleted = 0';
    let params = [];

    if (search) {
      whereClause += ' AND (username LIKE ? OR name LIKE ? OR phone LIKE ?)';
      const searchParam = `%${search}%`;
      params.push(searchParam, searchParam, searchParam);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM sys_user ${whereClause}`,
      params
    );

    // 获取用户列表
    const [users] = await pool.execute(
      `SELECT id, username, name, phone, avatar, description, status, create_time, update_time 
       FROM sys_user ${whereClause} 
       ORDER BY create_time DESC 
       LIMIT ? OFFSET ?`,
      [...params, limit, offset]
    );

    res.json({
      success: true,
      message: '获取用户列表成功',
      data: {
        users,
        pagination: {
          page,
          limit,
          total: countResult[0].total,
          totalPages: Math.ceil(countResult[0].total / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    });
  }
});

// 更新用户状态（管理员功能）
router.put('/status/:id', async (req, res) => {
  try {
    const userId = req.params.id;
    const { status } = req.body;

    if (typeof status !== 'number' || (status !== 0 && status !== 1)) {
      return res.status(400).json({
        success: false,
        message: '状态值只能是0（禁用）或1（启用）'
      });
    }

    // 检查用户是否存在
    const [users] = await pool.execute(
      'SELECT id FROM sys_user WHERE id = ? AND is_deleted = 0',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 更新用户状态
    await pool.execute(
      'UPDATE sys_user SET status = ? WHERE id = ?',
      [status, userId]
    );

    res.json({
      success: true,
      message: '更新用户状态成功'
    });
  } catch (error) {
    console.error('更新用户状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户状态失败',
      error: error.message
    });
  }
});

// 删除用户（软删除）
router.delete('/:id', async (req, res) => {
  try {
    const userId = req.params.id;

    // 检查用户是否存在
    const [users] = await pool.execute(
      'SELECT id FROM sys_user WHERE id = ? AND is_deleted = 0',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 软删除用户
    await pool.execute(
      'UPDATE sys_user SET is_deleted = 1 WHERE id = ?',
      [userId]
    );

    res.json({
      success: true,
      message: '删除用户成功'
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({
      success: false,
      message: '删除用户失败',
      error: error.message
    });
  }
});

module.exports = router;